<?php
/**
 * Created by PhpStorm.
 * User: lenovo
 * Date: 2020/8/7
 * Time: 13:51
 */

namespace App\Services;


use App\Model\AppModel;
use App\Model\SupportPersonModel;
use App\Model\SupportPersonRelationModel;
use EasySwoole\ORM\DbManager;
use EasySwoole\EasySwoole\Config;

class SupportPersonService
{
    /**
     * 登录
     */
    public function login($param){
        try{
            #校验用户
            $suppoetPerson = SupportPersonModel::create()->get(['user_name'=>$param['user_name']]);
            if(empty($suppoetPerson)){
                return ReponseCodeService::CODE_SUPPORT_PERSON_MOBILE_NOT_EXIST;
            }
            #校验密码
            if($this->pwdCheck($param['password'],$suppoetPerson['password_hash'])){
                unset($suppoetPerson['password_hash'],$suppoetPerson['password_hash']);
                $suppoetPerson['head'] =  Config::getInstance()->getConf('APP.FILE_DOMAIN').$suppoetPerson['head'];
                return $suppoetPerson;
            }
           }catch(\Throwable $t){
            return ReponseCodeService::CODE_SERVICE_UNAVAILABLE;
        }
    }

    /**客服列表
     * @param $param
     */
    public function lists($param){
        try{
            $where = 'status = 1';
            if(isset($param['keyword'])&&!empty($param['keyword'])){
                $where = $where." and mobile like '%{$param['keyword']}%' or nickname like '%{$param['keyword']}%'";
            }
            $page = $param['page'];          // 当前页码
            $limit = $param['limit'];        // 每页多少条数据
            $model = SupportPersonModel::create()->limit($limit * ($page - 1), $limit)->withTotalCount();
           // 列表数据
            $list = $model->all($where);
            $result = $model->lastQueryResult();
           // 总条数
            $total = $result->getTotalCount();
            $reponse['total'] = $total;
            $reponse['list'] = $list;
            $reponse['page'] = $page;
            $reponse['limit'] = $limit;
            return $reponse;
          }catch(\Throwable $t){
          return   ReponseCodeService::CODE_SERVICE_UNAVAILABLE;
        }
    }

    /**
     * 创建客服
     */
    public function createService($param,$adminInfo){
        try{
            //开启事务
            DbManager::getInstance()->startTransaction();

            #创建客服
            $supportPersonData = array(
                'mobile'=>$param['mobile'],
                'password_hash'=>$param['mobile'],
                'nickname'=>$param['nickname'],
                'real_name'=>$param['real_name'],
                'head'=>$param['head'],
                'created_at'=>date("Y-m-d H:i:s"),
                'updated_at'=>date("Y-m-d H:i:s"),
            );

            #校验手机号是否重复登记
            if(SupportPersonModel::create()->get(['mobile'=>$param['mobile']])){
                DbManager::getInstance()->rollback();
                return ReponseCodeService::CODE_SUPPORT_PERSON_MOBILE_EXIST;
            }

            $id = SupportPersonModel::create()->data($supportPersonData)->save();
            #绑定用户组
            $supportPersonRelationData = array(
                'support_person_id'=>$id,
                'created_at'=>date("Y-m-d H:i:s"),
                'updated_at'=>date("Y-m-d H:i:s"),
            );
            $appIdArr = explode(',',$param['app_ids']);
            if(sizeof($appIdArr)<=0){
                DbManager::getInstance()->rollback();
                return ReponseCodeService::CODE_FAILE;
            }

            #有app不存在，直接失败
            foreach ($appIdArr as $appId){
                if(!AppModel::create()->get(['id'=>$appId])){
                    DbManager::getInstance()->rollback();
                    return ReponseCodeService::CODE_FAILE;
                }
                #创建app客服关联信息
                $supportPersonRelationData['app_id'] = $appId;
                SupportPersonRelationModel::create()->data($supportPersonRelationData)->save();
            }

        } catch(\Throwable  $e){
            //回滚事务
            DbManager::getInstance()->rollback();
            return ReponseCodeService::CODE_FAILE;
        } finally {
            //提交事务
            DbManager::getInstance()->commit();
        }
        return ReponseCodeService::CODE_OK;
    }




    /**修改客服信息
     * @param $param
     * @param $adminInfo
     */
    public function updateService($param,$adminInfo){
        try{
            //开启事务
            DbManager::getInstance()->startTransaction();
            if(isset($param['mobile'])){
                #校验手机号是否重复登记
                if(SupportPersonModel::create()->get(['mobile'=>$param['mobile']])){
                    DbManager::getInstance()->rollback();
                    return ReponseCodeService::CODE_SUPPORT_PERSON_MOBILE_EXIST;
                }
            }
            $id = $param['id'];
            unset($param['id']);
            #更新客服
            SupportPersonModel::create()->update($param,$param,['id'=>$id]);
            #绑定用户组
            $supportPersonRelationData = array(
                'support_person_id'=>$id,
                'created_at'=>date("Y-m-d H:i:s"),
                'updated_at'=>date("Y-m-d H:i:s"),
            );
            $appIdArr = explode(',',$param['app_ids']);
            if(sizeof($appIdArr)>0){
                #删除旧的关系
                SupportPersonRelationModel::create()->destroy(['support_person_id'=>$id]);
                #有app不存在，直接失败
                foreach ($appIdArr as $appId){
                    if(!AppModel::create()->get(['id'=>$appId])){
                        DbManager::getInstance()->rollback();
                        return ReponseCodeService::CODE_FAILE;
                    }
                    #创建app客服关联信息
                    $supportPersonRelationData['app_id'] = $appId;
                    SupportPersonRelationModel::create()->data($supportPersonRelationData)->save();
                }
            }
        } catch(\Throwable  $e){
            //回滚事务
            DbManager::getInstance()->rollback();
            return ReponseCodeService::CODE_FAILE;
        } finally {
            //提交事务
            DbManager::getInstance()->commit();
        }
        return ReponseCodeService::CODE_OK;
    }

    /**
     * 密码加密
     */
    function pwdEncode($password){
        return md5($password.md5(Config::getInstance()->getConf('PWD_SALT')));
    }

    /**
     * @param $password密码
     * @param $encodePassword密文
     */
    function pwdCheck($password,$encodedPassword){
        if($this->pwdEncode($password)==$encodedPassword){
            return true;
        }
        return false;
    }
}